#!/usr/bin/env python3
# -*- coding: utf-8 -*- 
import tkinter as tk
from tkinter.constants  import *
from tkinter.messagebox import showinfo, showerror
from tkinter.filedialog import askdirectory, askopenfilename
# For plot
#from mpl_toolkits.mplot3d import Axes3D
#import matplotlib
#import matplotlib.pyplot as plt
# Local import
import cube
import kmeans
import resultats
#import xmltest  DO OT WORKS YET BEACAUSE BIOPYTHON DO NOT SUPPORT PYTHON 3.0

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.master.title("Data Mining")
        self.grid(sticky=N+S+E+W)
        
        # Init variable
        self.directory      = tk.StringVar()
        self.xmlFile        = tk.StringVar()
        self.interCluster   = tk.StringVar()
        self.intraCluster   = tk.StringVar()
        self.c              = None
        self.clusters       = None
        self.directory.set("Aucun")
        self.xmlFile.set("Aucun")
        self.interCluster.set("Aucun")
        self.intraCluster.set("Aucun")
        
        self.createWidgets()
        
    def createWidgets(self):
        self.createWindow()
        self.createMenu()
        self.createContent()

    def createWindow(self):
        # Create Main window
        self.top=self.winfo_toplevel ()
        #self.top.geometry            ("1280x900+300+0")

    def createMenu(self):
        # Create Menu
        menuBar         = tk.Menu(self.top)
        self.top["menu"]= menuBar
        helpSubMenu     = tk.Menu(menuBar)
        appSubMenu      = tk.Menu(menuBar)
        menuBar.add_cascade     (label="Application" , menu      = appSubMenu)
        appSubMenu.add_command  (label="Quit"        , command   = self.quit)
        menuBar.add_cascade     (label="Help"        , menu      = helpSubMenu)
        helpSubMenu.add_command (label="About"       , command   = self.__aboutHandler)
    
    def createContent(self):
        # Dir Dialog
        self.directoryButton= tk.Button(self.top, text = 'Choose pdb directory', command = lambda : self.getDirname())
        self.directoryLabel	= tk.Label(self.top , textvariable = self.directory, fg = 'green')
        # File Dialog
        self.xmlFileButton  = tk.Button(self.top, text = 'Choose xml file', command = lambda : self.getFilename())
        self.xmlFileLabel   = tk.Label(self.top , textvariable = self.xmlFile, fg = 'blue')
        # Plot
        self.plotButton     = tk.Button(self.top, text = 'show plot', command = lambda : self.drawGraph())
        # Distance
        self.distanceButton = tk.Button(self.top, text = 'get distance', command = lambda : self.getFilename())
        self.distanceLabel  = tk.Label(self.top , text = "Distance", fg = 'black')
        self.interLabel     = tk.Label(self.top , textvariable= self.interCluster, fg = 'purple')
        self.intraLabel     = tk.Label(self.top , textvariable= self.intraCluster, fg = 'red')
        # Resultat
        self.resText        = tk.Text(self.top, state=DISABLED)
        self.resText.config(font=('courier', 15, 'normal'))
        # List
        self.listbox        = tk.Listbox(self.top, height=6)
        for line in ['Hydrophobe, Longueur, pI, Chaine, Structure','Hydrophobe, Structure, Chaine,  pI, Longueur','pI, Hydrophobe, Longueur, Chaine, Structure','pI, Longueur, Hydrophobe, Chaine, Structure']:
            self.listbox.insert(END, line)
        self.listbox.bind('<Double-1>', self.handleList)
        # Placement
        self.directoryButton.grid   (row=0,            column=0,                sticky=N+S+E+W)
        self.directoryLabel.grid    (row=0,            column=1, columnspan=2,  sticky=N+S+E+W)
        self.xmlFileButton.grid     (row=1,            column=0,                sticky=N+S+E+W)
        self.xmlFileLabel.grid      (row=1,            column=1, columnspan=2,  sticky=N+S+E+W)
        self.plotButton.grid        (row=2,            column=0,                sticky=N+S+E+W)
        self.listbox.grid           (row=2,            column=1, columnspan=2,  sticky=N+S+E+W)
        self.resText.grid           (row=3,            column=0,                sticky=N+S+E+W)
        self.interLabel.grid        (row=3,            column=1,                sticky=N+S+E+W)
        self.intraLabel.grid        (row=3,            column=2,                sticky=N+S+E+W)
        self.grid_columnconfigure(0,weight=1)
        self.update()
        
    def __aboutHandler(self):
        showinfo("About","Authors: Nicolas FONTAINE, Florence MAURIER, Jonathan MERCIER")

    def getDirname(self):
        dir = askdirectory(initialdir="/",title='Please select a directory')
        if not dir:
            self.directory.set("Aucun")
        else:
            self.xmlFile.set("result.xml")
            #xmltest.compute(self.xmlFile.get()) DO OT WORKS YET BEACAUSE BIOPYTHON DO NOT SUPPORT PYTHON 3.0
            self.c          = cube.build(self.xmlFile.get())
            self.clusters   = cube.premierCluster(self.c)
            self.directory.set(dir)
            
    def getFilename(self):
        texfile = askopenfilename(filetypes = [("Fichiers xml", "*.xml")])
        if not texfile:
            self.xmlFile.set("Aucun")
        else:
            self.xmlFile.set(texfile)
            self.c          = cube.build(self.xmlFile.get())
            self.clusters   = cube.premierCluster(self.c)

    def run(self, item):
        for index in item:
            index = int(index)
            clusterStructure = None
            if(index == 0):
                clustersHydrophobe  = kmeans.compute(self.clusters,  3, 51, self.c, "proprietes", "AA_hydrophobes")
                clusterLongueur     = cube.clusterisationT (clustersHydrophobe, self.c)
                clusterspI          = cube.clusterisationK(clusterLongueur,self.c,  3, 51,  "proprietes", "pI")
                clusterChaine       = cube.clusterisationC(clusterspI, self.c)
                clusterStructure    = cube.clusterisationS(clusterChaine, self.c)
            elif(index == 1):
                clustersHydrophobe  = kmeans.compute(self.clusters,  3, 51, self.c, "proprietes","AA_hydrophobes")
                clusterStructure    = cube.clusterisationS(clustersHydrophobe, self.c)
                clusterChaine       = cube.clusterisationC(clusterStructure, self.c)
                clusterspI          = cube.clusterisationK(clusterChaine, self.c,  3, 51, "proprietes", "pI")
                clusterLongueur     = cube.clusterisationT (clusterspI, self.c)
            elif(index == 2):
                clusterspI          = kmeans.compute(self.clusters,  3, 51, self.c, "proprietes", "pI")
                clustersHydrophobe  = cube.clusterisationK(clusterspI,self.c,  3, 51,  "proprietes", "AA_hydrophobes")
                clusterLongueur     = cube.clusterisationT (clustersHydrophobe, self.c)
                clusterChaine       = cube.clusterisationC(clusterLongueur, self.c)
                clusterStructure    = cube.clusterisationS(clusterChaine, self.c)
            elif(index == 3):
                clusterspI          = kmeans.compute(self.clusters,  3, 51, self.c, "proprietes", "pI")
                clusterLongueur     = cube.clusterisationT (clusterspI, self.c)	
                clustersHydrophobe  = cube.clusterisationK(clusterLongueur,self.c,  3, 51,  "proprietes", "AA_hydrophobes")
                clusterChaine       = cube.clusterisationC(clustersHydrophobe, self.c)
                clusterStructure    = cube.clusterisationS(clusterChaine, self.c)
            #ecriture des resultats
            resultats.resultats(self.c,clusterStructure)
            self.resText.config(state=NORMAL)
            self.resText.delete(1.0, END)
            content=open("resultats_clusterisation.txt","r")
            self.resText.insert(END,content.read())
            content.close()
            self.resText.config(state=DISABLED)
            
            #strategie bottom up
            distances       = cube.matrice_distances.matrice_generale(self.c)
            quality         = cube.qualite_clusterisation.qualite_clusterisation(distances, clusterStructure)
            self.interCluster.set("Min: "+str(quality[0]))
            self.intraCluster.set("Max: "+str(quality[1]))
        
    def handleList(self, event):
        index = self.listbox.curselection()          
        label = self.listbox.get(index)                
        self.run(index)
        
    def drawGraph():
        for c in self.clusters:
            if len(c)!=1:
                for indice in c:
                    self.c["proprietes"]['AA_hydrophobes'][indice]
if __name__ == "__main__":
        app = Application()
        app.update()
        app.mainloop()